from dataclasses import dataclass

from src.application.user import dto
from src.application.user.converters import convert_active_user_entity_to_dto
from src.application.user.uow import UserUoW
from src.domain.user.value_objects import TelegramUserId, UserEmail


@dataclass(frozen=True)
class RegisterUser:
    tg_user_id: int
    email: str


class RegisterUserHandler:
    """Регистрация пользователя"""

    def __init__(self, *, uow: UserUoW) -> None:
        self._uow = uow

    async def __call__(self, command: RegisterUser) -> dto.UserDTO:
        user_id = TelegramUserId(value=command.tg_user_id)
        user_email = UserEmail(value=command.email)

        user = await self._uow.user_repo.acquire_user_by_id(user_tg_id=user_id)
        print(user)
        user.register_user(user_email)
        print(user)
        try:
            await self._uow.user_repo.update_user(user=user)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        user_dto = convert_active_user_entity_to_dto(user)

        return user_dto
